package com.say.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.say.bean.domain.User;
import com.say.framework.core.util.SystemResourceLocator;
import com.say.service.UserService;
import com.say.utils.weixin.AdvancedUtil;
import com.say.utils.weixin.WeixinOauth2Token;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserUtil {
	
	private static Logger logger = LoggerFactory.getLogger(UserUtil.class);
	/**
    * 从微信接口进来获取微信用户的基本信息
    */
	public static void getUserInfo(String openId,HttpServletRequest request){
		if(openId !=null){
			request.getSession().setAttribute("openId", openId);
			User user=(User) request.getSession().getAttribute("user");
			if(user==null){
				logger.info("seession 中 user为空");
				UserService userService=(UserService) SystemResourceLocator.getBean(UserService.class);
				  user=userService.getUserByOpenId(openId);
				if(user==null){
					logger.info("数据库中 中 user为空");
//					String accessToken=tokenManager.getSSJAccessToken();
					user=UserHandlerUtil.getUserInfo(null, openId);
					user=userService.insertUser(user);
					logger.info("数据库中 中 userId为"+user.getId());
				}
				request.getSession().setAttribute("user", user);
				request.getSession().setAttribute("userId", user.getId());
			}
		} 
	}
	
	public static String getOpenId(String code){
		WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(code);
		return  token.getOpenId();
	}
	/**
     * 从微信网页进去分享进来
	 * @throws Exception 
     */
	public static  boolean  WeixinOauth2(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String openId=(String) request.getSession().getAttribute("openId"); 
		logger.info("从微信网页分享进来获取  ---openId----)"+openId);
		StringBuffer url  =  new StringBuffer(request.getRequestURL());
		if(openId==null){
			String queryurl= request.getQueryString();
			if(null!=queryurl){  
				url.append("?"+queryurl);
			} 
        	String code = request.getParameter("code");
        	if(code !=null){
        		WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(code);
        		if(token ==null || (token !=null && token.getAccessToken()==null)){
            		response.sendRedirect(AdvancedUtil.getbaseurl(url.toString().replaceAll("(" + "code" + "=[^&]*)","").replaceAll("&&", "&")));
            		return false;
        		}
        		UserService userService=(UserService) SystemResourceLocator.getBean(UserService.class);
        		User user=userService.getUserByOpenId(token.getOpenId());
        		if(user==null){
        			if(token.getScope() !=null && token.getScope().contains("snsapi_base")){
        				response.sendRedirect(AdvancedUtil.getuserinfourl(url.toString().replaceAll("(" + "code" + "=[^&]*)","").replaceAll("&&", "&")));
        				return false;
        			}else if(token.getScope() !=null && token.getScope().contains("snsapi_userinfo")){
        				user= AdvancedUtil.getUserInfo(token.getAccessToken(), token.getOpenId());
        				user=userService.insertUser(user);
        				request.getSession().setAttribute("openId",token.getOpenId());
        				request.getSession().setAttribute("user", user);
        				return true;
        			}else{
        				return false;
        			}
        		}else{
        			request.getSession().setAttribute("openId",token.getOpenId());
        			request.getSession().setAttribute("user", user);
        			return true;
        		}
        	}else{
        		logger.info("从微信网页分享进来  ---code为空snsapi_base----) 发起获取用户的基本信息");
        		response.sendRedirect(AdvancedUtil.getbaseurl(url.toString().replaceAll("(" + "code" + "=[^&]*)","").replaceAll("&&", "&")));
        		return false;
        	}
        }else{
        	return true;
        }
	}
	
	//获取用户信息
	public static User getUser(HttpServletRequest request){
		HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user==null){
        	String userId=(String) session.getAttribute("userId");
        	if(StringUtils.isEmpty(userId)) {
        		userId=CookiesUtil.getCookieByName(request, "_t");
        	}
        	if(userId !=null){
        		UserService userService= SystemResourceLocator.getBean(UserService.class);
        		user=userService.getById(userId);
        		request.getSession().setAttribute("user", user);
        		request.getSession().setAttribute("userId", userId);
        	}
        }
		return user;
	}
	
	//获取用户ID
	public static String getUserId(HttpServletRequest request){
		 User user = UserUtil.getUser(request);
	    return user!=null&&user.getId()!=null?user.getId():"1";
	}
	//获取用户ID
	public static String getOpenId(HttpServletRequest request){
		User user = UserUtil.getUser(request);
		return user!=null&&user.getOpenId()!=null?user.getOpenId():"1";
	}
}
